package com.ktjiaoyu.ktmall.service.impl;

import com.ktjiaoyu.ktmall.dao.CategoryDao;
import com.ktjiaoyu.ktmall.dao.impl.CategoryDaoImpl;
import com.ktjiaoyu.ktmall.entity.Category;
import com.ktjiaoyu.ktmall.service.CategoryService;

import java.util.ArrayList;
import java.util.List;

public class CategoryServiceImpl implements CategoryService {
    private final CategoryDao categoryDao = new CategoryDaoImpl();
    @Override
    public List<Category> findAll() {
        return categoryDao.findAll();
    }

    @Override
    public List<Category> findTree() {
        List<Category> all = categoryDao.findAll();
        return buildTree(all,"0");
    }

    private List<Category> buildTree(List<Category> all, String parentId) {
        List<Category> tree = new ArrayList<>();
        for(Category cat : all) {
            if (cat.getParentId() != null && cat.getParentId().equals(parentId)) {
                List<Category> children = buildTree(all, cat.getId());
                cat.setChildren(children);
                tree.add(cat);
            }
        }
        return tree;
    }

}
